package com.dyh.quickdemo.demos.timingTask;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;

import java.util.concurrent.*;
import java.util.function.Function;

/*
@Author=Joey Wheeler
@Date=2020/10/21 14:24
有执行时间限制的Function
*/
@Setter@Getter@AllArgsConstructor
public class TimingFcV2<T,R> implements Function<T,R> {

    private long limitMilliseconds;
    private Function<T,R> core;
    private Function<T,R> fallBack;
    private ExecutorService executor;

    @SneakyThrows
    @Override
    public R apply(T t) {
        R r = null;
        try {
            Future<R> coreFuture=executor.submit(()->core.apply(t));
            r = coreFuture.get(limitMilliseconds,TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            r = fallBack.apply(t);
        }
        catch (Exception e){
            /**/
        }
        return r;
    }


    public static void main(String[] args) {
        Function<String,Integer> fun = s->{
            try {
                Thread.sleep(s.length()*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return s.length();
        };

       // ScheduledThreadPoolExecutor threadPoolExecutor =new ScheduledThreadPoolExecutor(1);
        /*ForkJoinPool.commonPool() 没用*/
        TimingFcV2<String,Integer> timingFc = new TimingFcV2(2000,fun, s->-1,ForkJoinPool.commonPool());

        Object res1 = timingFc.apply("12");
        System.out.println(res1);

        Object res2 = timingFc.apply("123");
        System.out.println(res2);
    }

}
